<!-- src/components/TopNav.vue -->
<template>
  <header class="top-nav">
    <!-- 左侧LOGO -->
    <div class="logo">
      <img src="@/assets/images/logo.jpg" alt="网站Logo" />
      <span>全都有网上超市</span>
    </div>

    <!-- 中间搜索框 -->
    <div class="search-box">
      <input
        type="text"
        placeholder="搜索..."
        @focus="goToSearch"
      />
    </div>

    <!-- 中间导航菜单 -->
    <nav class="nav-menu">
      <router-link to="/home" active-class="active">首页</router-link>
      <!-- 下拉菜单包裹元素 -->
      <el-dropdown
        v-if="isLoggedIn"
        ref="dropdown"
        @command="handleDropdownCommand"
        placement="bottom-start"
        trigger="click"
      >
        <span class="dropdown-link">
          个人资料<i class="el-icon-arrow-down el-icon--right"></i>
        </span>
        <template #dropdown>
          <el-dropdown-menu class="custom-dropdown-menu">
            <el-dropdown-item command="viewProfile">查看资料</el-dropdown-item>
            <el-dropdown-item command="changePassword">更新密码</el-dropdown-item>
            <el-dropdown-item command="logout" divided>注销账号</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
      
      <!-- 未登录时显示登录链接 -->
      <router-link v-else to="/login" class="nav-link">登录</router-link>

      <!-- 我的订单下拉菜单 -->
      <el-dropdown
        v-if="isLoggedIn"
        @command="handleOrderDropdownCommand"
        placement="bottom-start"
        trigger="click"
      >
        <span class="dropdown-link">
          我的订单<i class="el-icon-arrow-down el-icon--right"></i>
        </span>
        <template #dropdown>
          <el-dropdown-menu class="custom-dropdown-menu">
            <el-dropdown-item command="allOrders">所有订单</el-dropdown-item>
            <el-dropdown-item command="myCart">我的购物车</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </nav>

    <!-- 右侧用户信息 -->
    <div class="user-info">
      <el-avatar :size="30" :src="displayUserAvatar"></el-avatar>
      <span class="username">{{ displayUsername }}</span>
    </div>
  </header>
</template>

<script>
import defaultAvatar from '@/assets/images/user-avatar.jpg'

export default {
  name: 'TopNav',
  data() {
    return {
      defaultAvatar: defaultAvatar,
      userAvatar: defaultAvatar
    }
  },
  computed: {
    userInfo() {
      return this.$store.getters.getUserInfo
    },
    isLoggedIn() {
      // 检查用户是否已登录
      return this.userInfo && this.userInfo.username
    },
    displayUsername() {
      // 如果已登录，显示用户名；否则显示"未登录"
      return this.isLoggedIn ? this.userInfo.username : '未登录'
    },
    displayUserAvatar() {
      // 如果用户已登录且有自定义头像，则显示自定义头像，否则显示默认头像
      return this.isLoggedIn && this.userAvatar ? this.userAvatar : this.defaultAvatar
    }
  },
  watch: {
    userInfo: {
      handler() {
        this.loadUserAvatar()
      },
      deep: true
    }
  },
  created() {
    this.loadUserAvatar()
  },
  methods: {
    handleDropdownCommand(command) {
      if (command === 'viewProfile') {
        this.$router.push('/profile')
      } else if (command === 'changePassword') {
        const { username } = this.userInfo
        this.$router.push({
          name: 'reset',
          params: this.userInfo.username ? { username } : {}
        })
      } else if (command === 'logout') {
        this.logout()
      }
    },

    handleOrderDropdownCommand(command) {
      if (command === 'allOrders') {
        this.$router.push('/orders')
      } else if (command === 'myCart') {
        this.$router.push('/cart')
      }
    },

    logout() {
      this.$confirm('确定要退出登录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$store.commit('SET_USER_INFO', {
          username: null,
          password: null,
          position: null
        })
        this.$message.success('已退出')
        this.$router.push('/login') 
      }).catch(() => {
        this.$message.info('已取消')
      })
    },

    goToSearch() {
      this.$router.push('/search').then(() => {
        this.$nextTick(() => {
          const searchInput = document.getElementById('search-input');
          if (searchInput) {
            searchInput.focus(); 
          }
        });
      });
    },

    // 加载用户头像
    loadUserAvatar() {
      if (!this.isLoggedIn) {
        this.userAvatar = this.defaultAvatar
        return
      }

      const userAvatarKey = `avatar_${this.userInfo.username}`
      const savedAvatar = localStorage.getItem(userAvatarKey)
      this.userAvatar = savedAvatar || this.defaultAvatar
    }
  }
}
</script>

<style scoped>
.top-nav {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #2e7d32; 
  color: white;
  padding: 10px 20px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 999;
}

.logo {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
}

.logo img {
  height: 40px;
  margin-right: 10px;
}

.search-box {
  flex: 1;
  max-width: 300px;
  margin-left: 20px;
}

.search-box input[type="text"] {
  width: 100%;
  padding: 6px 12px;
  border-radius: 4px;
  border: none;
  outline: none;
  background-color: #e8f5e9;
  color: #2e7d32;
  transition: border-color 0.3s;
}

.search-box input:focus {
  border: 1px solid #ffee58;
}

.nav-menu {
  display: flex;
  gap: 20px;
  margin-left: 20px;
}

.nav-menu a {
  color: white;
  text-decoration: none;
  line-height: 40px;
  transition: color 0.3s;
}

.nav-menu a:hover,
.nav-menu a.active {
  color: #ffee58;
}

.nav-link {
  color: white;
  text-decoration: none;
  line-height: 40px;
  transition: color 0.3s;
}

.nav-link:hover {
  color: #ffee58;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.user-info .username {
  font-weight: bold;
}

.dropdown-link {
  cursor: pointer;
  color: white;
  font-size: 14px;
  padding: 0 10px;
  line-height: 40px; 
}

.dropdown-link:hover {
  color: #ffd700;
}

.custom-dropdown-menu {
  background-color: #ffffff !important; 
  color: #333333 !important; 
  border: 1px solid #ebebeb; 
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1); 
}

.custom-dropdown-menu .el-dropdown-menu__item {
  color: #333333 !important; 
  padding: 10px 20px; 
}

.custom-dropdown-menu .el-dropdown-menu__item:hover {
  background-color: #f5f7fa !important; 
  color: #333333 !important; 
}

.custom-dropdown-menu .el-dropdown-menu__item.is-divided:before {
  background-color: #ebebeb !important; 
}
</style>